import axios from "axios";
import { LitElement, html, css, PropertyValueMap } from "lit";
import { classMap } from "lit/directives/class-map.js";
import { customElement, property, query } from "lit/decorators.js";
import { createRef, Ref, ref } from "lit/directives/ref.js";
import { when } from "lit/directives/when.js";
import { map } from "lit/directives/map.js";
import { choose } from "lit/directives/choose.js";
import "./preview";

interface ColorJson {
  itemBoxShadow: unknown;
  itemBorderRadius: unknown;
  itemBackground: unknown;
  itemFill: string;
  pageBackground: string;
  menu: string;
  hoverMenu: string;
  textInMenu: string;
  activeTextInMenu: string;
  hoverTextInMenu: string;
  primary: string;
  secondary: string;
  textPrimary: string;
  textRegular: string;
  textSecondary: string;
  textInPlaceholder: string;
  textDisabled: string;
  error: string;
  warning: string;
  success: string;
  background: string;
  disabled: string;
  itemBorderColor: string;
  colorScheme: string;
  colorWhite: string;
  colorBlack: string;
}

@customElement("ai-colorpicker")
export class AiColorpicker extends LitElement {
  static styles = [
    css`
      :host {
        display: flex;
        flex-direction: column;
        align-items: center;
        height: 100vh;
        align-items: stretch;
        overflow: hidden;
      }

      .chats {
        overflow: hidden;
        display: flex;
        flex-direction: column;
        width: calc(100% - 24px);
        padding: 12px;
        background-color: #fff;
        border-radius: 4px;
        margin: 12px;
        flex: 1;

        .messages {
          display: flex;
          flex-direction: column;
          flex: 1;
          overflow: auto;
          min-height: 120px;

          .message {
            padding: 10px;
            margin: 10px;
            max-width: 80%;
            display: flex;
            flex-direction: row;
            align-items: flex-start;

            span {
              box-shadow: 0 1px 4px 0px #ccc;
              background-color: #f5f5f5;
              word-wrap: break-word;
              border-radius: 4px;
              padding: 10px;
            }

            &::before,
            &::after {
              color: #333;
              font-size: 12px;
            }

            &::before {
              margin-right: 5px;
            }

            &::after {
              margin-left: 5px;
            }

            &.user {
              align-self: flex-end;

              span {
                background-color: #e4e4e4;
                color: #000;
              }

              &::after {
                content: "你";
                font-weight: bold;
              }
            }

            &.assistant {
              align-self: flex-start;

              span {
                color: #e4e4e4;
                background-color: #000;
              }

              &::before {
                content: "文心";
                font-weight: bold;
              }
            }

            &.loading {
              align-self: flex-start span {
                color: #e4e4e4;
                background-color: #463300;
              }

              &::before {
                content: "文心";
                font-weight: bold;
              }
            }
          }
        }

        .chat-input {
          display: flex;
          flex-direction: row;
          width: calc(100% + 20px);
          margin: 0 -20px -20px -20px;
          box-shadow: 0 -1px 4px 0px #ccc;
          padding: 10px;

          textarea {
            flex: 1;
            padding: 10px;
            margin: 0;
            border: none;
            border-radius: 0;
            box-sizing: border-box;
          }

          button {
            border: none;
            padding: 10px;
            margin: 0;
            border-radius: 0px;
            background-color: #e4e4e4;
            color: #000;
            width: 60px;
          }
        }
      }

      .top {
        display: flex;
        flex-direction: column;
        background-color: rgb(14, 17, 23);
        color: #fff;

        nav {
          display: flex;
          flex-direction: row;
          width: 100%;
          height: 50px;
          padding: 0;

          h1 {
            margin: 0;
            font-size: 24px;
            padding: 10px;

            .small {
              font-size: 14px;
              color: #ccc;
            }
          }

          > span {
            font-size: 14px;
            height: 50px;
            line-height: 50px;
            display: flex;
            padding: 0 10px;

            &.selected,
            &:hover {
              background-color: #333;
            }

            &.disabled {
              color: #666;
            }
          }

          > .flex {
            flex: 1;
          }
        }

        p {
          margin: 5px 0 12px 0;
          font-size: 14px;
        }

        button {
          border: 1px solid #ccc;
          padding: 10px;
          margin: 10px 0;
          border-radius: 4px;
          background-color: #e4e4e4;
          color: #000;
          width: 100%;
        }
      }

      .response {
        flex: 1;
        display: block;
        flex-direction: column;
        align-items: center;
        background-color: #f5f5f5;
        padding: 20px;
        overflow: scroll;
      }

      input {
        width: 100%;
        padding: 8px;
        margin: 5px 0;
        border: 1px solid #ccc;
        border-radius: 4px;
        box-sizing: border-box;
      }

      textarea {
        width: 100%;
        padding: 10px;
        margin: 10px 0;
        border: 1px solid #ccc;
        border-radius: 4px;
        box-sizing: border-box;
      }

      .footer {
        margin-top: 20px;
        display: flex;
        flex-direction: column;
        align-items: center;
        font-size: 10px;
        justify-content: end;
        p {
          margin: 3px;
          line-height: 1.1;
        }

        a {
          color: #1b1b1b;
        }
      }

      .radio-group {
        display: flex;
        justify-content: center;
        width: 100%;
        margin: 10px 0;
        align-items: center;
        label {
          display: flex;
          align-items: center;
          width: 150px;
        }
        input {
          margin-right: 5px;
          word-break: keep-all;
          width: 20px;
        }
      }

      main {
        display: flex;
        flex-direction: column;
        padding: 20px;
        width: 100%;
        box-sizing: border-box;
        background-color: #f5f5f5;
        min-height: 600px;

        > .panel {
          display: flex;
          flex: 1;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          padding: 20px;
          width: 100%;
          box-sizing: border-box;
          background-color: #fff;
          box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
          border-radius: 4px;

          p {
            margin: 10px 0;
            font-size: 14px;
          }

          .block-button {
            width: 100%;
            border: 1px solid #ccc;
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
            background-color: #e4e4e4;
            color: #000;

            &.success {
              background-color: #28a745;
              color: #fff;
            }
          }
        }

        input {
          width: 100%;
          padding: 8px;
          margin: 5px 0;
          border: 1px solid #ccc;
          border-radius: 4px;
          box-sizing: border-box;
        }
        .radio-group {
          display: flex;
          justify-content: center;
          width: 100%;
          margin: 10px 0;
          align-items: center;
          label {
            display: flex;
            align-items: center;
            width: 150px;
          }
          input {
            margin-right: 5px;
            word-break: keep-all;
            width: 20px;
          }
        }
      }

      @media (max-width: 768px) {
        :host {
          flex-direction: column;
          height: auto;
        }

        .top {
          width: auto;

          .chats {
            min-height: 300px;
          }
        }

        .response {
          width: 100%;
        }
      }
    `,
  ];

  accessTokenRef: Ref<HTMLInputElement> = createRef();

  accessToken: string = "";

  @property({ type: Array, state: true })
  messages: { role: string; content: string }[] = [];

  @query("textarea#description")
  description: any;

  @query("input[name=model]:checked")
  modelRef: any;

  @property({ type: String, state: true })
  model: string = "completions";

  @query("input[name=frametype]:checked")
  framework: any;

  @property({ type: Boolean, state: true })
  notConfiged: boolean = true;

  @property({ type: Boolean, state: true })
  receivedResponse: boolean = false;

  @property({ type: Object, state: true })
  aiResult: {
    parsed: boolean;
    json: ColorJson | null;
    description: string;
  } = {
    parsed: false,
    json: null,
    description: "这是一个使用文心一言为你的软件选择主题配色的工具",
  };

  @property({ type: Number, state: true })
  selectedPanel: number = 0;

  prompt: string =
    "你是一个软件设计师，你需要根据客户提供的软件介绍，为他们选择合适的主题配色，配色颜色包括菜单配色，文字配色和主要元素配色，你应该首先选择使用深色或者浅色主题，然后根据用户的选择决定界面是偏活泼还是偏安静，" +
    "活泼界面菜单和组件元素的颜色应该更鲜亮，安静界面菜单和组件元素的颜色和背景色差异更小，然后决定页面的基准白色和基准黑色，安静界面的基准白色和基准黑色更趋向于常见的白色和黑色，活泼页面可以根据页面风格变换，然后根据选择的主题和用户的要求，选择合适的文字和元素颜色(颜色可以使用rgb，如果需要在item中体现透明效果，可以使用rgba)，菜单颜色和主体背景色应该有明显区别,浅色背景使用深色菜单，深色背景使用透明或者浅色菜单,页面的主要色系不应该操作三个，主要文字颜色应比次要文字颜色更突出，再决定界面是纯平面显示还是元素间有层次，并以此决定itemBoxShadow属性，你的返回只能以下面的格式返回：" +
    '```json\n{\n "colorScheme": "(light|dark)",\n "colorWhite": "(页面中的基准白色)",\n "colorBlack": "(页面中的基准黑色)",\n"textPrimary": "(页面强调文字颜色)",\n "textRegular": "(页面一般文字颜色)",\n "textSecondary": "(页面次要文字颜色)",\n "textDisabled": "(页面不可用文字颜色)",' +
    '\n "menu": "(菜单背景颜色)",\n"textInMenu": "(菜单中文字颜色)",\n"activeTextInMenu": "(选中菜单的文字颜色)",\n"hoverTextInMenu": "(悬浮菜单的文字颜色)",\n"hoverMenu": "(悬浮菜单的背景颜色)",\n"itemBorderRadius": "(item的圆角大小)",\n"itemBorderColor": "(item的边缘颜色)",\n"itemBoxShadow": "(item的边缘阴影属性)",' +
    '\n  "pageBackground": "(页面背景颜色)",\n  "itemBackground": "(页面中card等控件的背景颜色)",\n"itemFill": "(页面中radio,checkbox等控件的颜色)",\n"primary": "(主要组件背景颜色)",\n"secondary": "(次要组件背景颜色)",' +
    '\n"error": "(错误提示组件背景颜色)",\n"warning": "(警告提示组件背景颜色)","disabled": "(不可用组件背景颜色)",' +
    '\n"success": "(成功提示组件背景颜色)"\n}\n```,这是用户的要求：';

  get messagesToSend() {
    return this.messages.map((message, index) => {
      if (index == 0) {
        return {
          role: "user",
          content: this.prompt + message.content,
        };
      } else {
        return message;
      }
    });
  }

  AiColorpicker() {
    this.accessToken = localStorage.getItem("accessToken") || "";
    this.description = "";
  }

  cacheAccessToken() {
    this.accessToken = this.accessTokenRef.value?.value || "";
    if (this.accessToken) {
      localStorage.setItem("accessToken", this.accessToken);
    }
  }

  protected firstUpdated(
    _changedProperties: PropertyValueMap<any> | Map<PropertyKey, unknown>
  ): void {
    this.accessToken = localStorage.getItem("accessToken") || "";
    this.accessTokenRef.value!.value = this.accessToken;
  }

  begin() {
    this.accessToken = this.accessTokenRef.value?.value || "";
    this.model = this.modelRef.value;
    this.notConfiged = false;
    this.selectedPanel = 1;
  }

  submit() {
    const description = this.description.value;
    if (this.accessToken && description) {
      var url = "https://aistudio.baidu.com/llm/lmapi/v1/chat/" + this.model;
      this.messages.push({
        role: "user",
        content: description,
      });
      //clear input
      this.description.value = "";
      this.requestUpdate();
      var p: Promise<any>;
      p = axios.post(
        url,
        {
          messages: this.messagesToSend,
        },
        {
          headers: {
            "Content-Type": "application/json",
            Authorization: "token " + this.accessToken,
          },
        }
      );
      // p = new Promise((resolve, reject) => {
      //   var testRes = {
      //     logId: "2b3917ba62717199d309cb8d583f719d",
      //     errorCode: 0,
      //     errorMsg: "success",
      //     result: {
      //       id: "as-gsmb68d266",
      //       object: "chat.completion",
      //       created: 1713063493,
      //       result:
      //         '```json\n{\n "colorScheme": "light",\n "colorWhite": "#FFFFFF",\n "colorBlack": "#000000",\n "textPrimary": "#333333",\n "textRegular": "#666666",\n "textSecondary": "#999999",\n "textDisabled": "#CCCCCC",\n "menu": "#F5F5F5",\n "textInMenu": "#333333",\n "activeTextInMenu": "#FF6600",\n "hoverTextInMenu": "#FF6600",\n "hoverMenu": "#EEEEEE",\n "itemBorderRadius": "4px",\n "itemBorderColor": "rgba(0,0,0,0.1)",\n "itemBoxShadow": "0 2px 4px rgba(0,0,0,0.1)",\n "pageBackground": "#FFFFFF",\n "itemBackground": "#FFFFFF",\n "itemFill": "#FF6600",\n "primary": "#FFECB3",\n "secondary": "#FFFFFF",\n "error": "#FF6666",\n "warning": "#FFCC66",\n "disabled": "#CCCCCC",\n "success": "#B3FFB3"\n}\n```',
      //       usage: {
      //         prompt_tokens: 537,
      //         completion_tokens: 288,
      //         total_tokens: 825,
      //       },
      //       is_truncated: false,
      //       finish_reason: "normal",
      //       need_clear_history: false,
      //     },
      //   };
      //   resolve({
      //     data: testRes,
      //   });
      // });
      p.then((response: any) => {
        this.receivedResponse = true;
        this.selectedPanel = 2;
        var data = response.data;
        if (data.errorCode) {
          alert(data.errorMsg);
        } else {
          try {
            if (this.messages[this.messages.length - 1].role === "loading") {
              this.messages[this.messages.length - 1] = {
                role: "assistant",
                content: data.result.result,
              };
            } else {
              this.messages.push({
                role: "assistant",
                content: data.result.result,
              });
            }

            this.aiResult = this.splitJsonAndDescription(data.result.result);
            this.fillJson();
          } catch (e) {
            console.log("解码失败" + e);
          }
        }
        this.requestUpdate();
      }).catch((error: any) => {
        console.log(error);
        alert("提交失败，请检查你的访问令牌是否正确");
      });
      this.messages.push({
        role: "loading",
        content: "正在加载中...",
      });
      this.requestUpdate();
    } else {
      alert("请填写软件介绍或者主色调");
    }
  }
  splitJsonAndDescription(result: string): any {
    var json = result.split("```json")[1].split("```")[0];
    //按行分割json,每一行去掉注释
    var lines = json.split("\n");
    for (var i = 0; i < lines.length; i++) {
      lines[i] = lines[i].split("//")[0];
    }
    json = lines.join("\n");
    var jsonObj = JSON.parse(json);
    var description =
      result.split("```json")[0] + result.split("```json")[1].split("```")[1];
    return { json: jsonObj, description, parsed: true };
  }

  selectPage(index: number) {
    this.selectedPanel = index;
  }

  fillJson() {
    // (textInPrimary + textSecondary) / 2 = textRegular
    if (this.aiResult.json) {
      this.aiResult.json.textRegular = this.mixColor(
        this.aiResult.json.textPrimary,
        this.aiResult.json.textSecondary
      );
      this.aiResult.json.textInPlaceholder = this.mixColor(
        this.aiResult.json.textSecondary,
        this.aiResult.json.textDisabled
      );
    }
  }

  mixColor(color1: string, color2: string) {
    var c1 = this.hexToRgb(color1);
    var c2 = this.hexToRgb(color2);
    var c3 = {
      r: Math.round((c1.r + c2.r) / 2),
      g: Math.round((c1.g + c2.g) / 2),
      b: Math.round((c1.b + c2.b) / 2),
    };
    return this.rgbToHex(c3);
  }

  hexToRgb(hex: string) {
    var bigint = parseInt(hex.slice(1), 16);
    return {
      r: (bigint >> 16) & 255,
      g: (bigint >> 8) & 255,
      b: bigint & 255,
    };
  }

  rgbToHex(rgb: { r: number; g: number; b: number }) {
    return (
      "#" +
      ((1 << 24) + (rgb.r << 16) + (rgb.g << 8) + rgb.b).toString(16).slice(1)
    );
  }

  lighter(colorJson: ColorJson, color: string, percent: number) {
    var map = colorJson as any;
    if (colorJson.colorScheme == "light") {
      return this.lighterColorV2(map[color], percent);
    } else {
      return this.darkerColorV2(map[color], percent);
    }
  }

  darker(colorJson: ColorJson, color: string, percent: number) {
    var map = colorJson as any;
    if (colorJson.colorScheme == "light") {
      return this.darkerColorV2(map[color], percent);
    } else {
      return this.lighterColorV2(map[color], percent);
    }
  }

  lighterColorV2(color: string, percent: number) {
    var num = parseInt(color.slice(1), 16);
    var originR = (num >> 16) & 0x00ff;
    var diffR = 255 - originR;
    var R = Math.round(originR + (diffR * percent) / 100);
    console.log(R);
    console.log(originR);
    console.log(diffR);
    var originB = (num >> 8) & 0x00ff;
    var diffB = 255 - originB;
    var B = Math.round(originB + (diffB * percent) / 100);
    var originG = num & 0x0000ff;
    var diffG = 255 - originG;
    var G = Math.round(originG + (diffG * percent) / 100);
    var newColor =
      "#" + (0x1000000 + R * 0x10000 + B * 0x100 + G).toString(16).slice(1);
    return newColor;
  }

  darkerColorV2(color: string, percent: number) {
    var num = parseInt(color.slice(1), 16);
    var originR = (num >> 16) & 0x00ff;
    var remainPercent = 100 - percent;
    var R = Math.round((originR * remainPercent) / 100);
    var originB = (num >> 8) & 0x00ff;
    var B = Math.round((originB * remainPercent) / 100);
    var originG = num & 0x0000ff;
    var G = Math.round((originG * remainPercent) / 100);
    var newColor =
      "#" + (0x1000000 + R * 0x10000 + B * 0x100 + G).toString(16).slice(1);
    return newColor;
  }

  // --el-color-primary: #409eff;
  // --el-color-primary-light-3: #79bbff; 24
  // --el-color-primary-light-5: #a0cfff; 40
  // --el-color-primary-light-7: #c6e2ff; 56
  // --el-color-primary-light-8: #d9ecff; 64
  // --el-color-primary-light-9: #ecf5ff; 72
  // --el-color-primary-dark-2: #337ecc; -8

  export() {
    var css = "";
    if (this.framework.value === "element-pro") {
      css = `/* Element Pro */
/* Colors */
:root {
    ${this.pageStyle}
}`;
    }
    //下载文件
    var blob = new Blob([css], { type: "text/css" });
    var url = URL.createObjectURL(blob);
    var a = document.createElement("a");
    a.href = url;
    a.download = "element-pro.css";
    a.click();
  }

  get pageStyle() {
    return `--el-color-primary: ${this.aiResult.json?.primary};
    --el-color-primary-light-3: ${this.lighter(
      this.aiResult.json!,
      "primary",
      30
    )};
    --el-color-primary-light-5: ${this.lighter(
      this.aiResult.json!,
      "primary",
      50
    )};
    --el-color-primary-light-7: ${this.lighter(
      this.aiResult.json!,
      "primary",
      70
    )};
    --el-color-primary-light-8: ${this.lighter(
      this.aiResult.json!,
      "primary",
      80
    )};
    --el-color-primary-light-9: ${this.lighter(
      this.aiResult.json!,
      "primary",
      90
    )};
    --el-color-primary-dark-2: ${this.darker(
      this.aiResult.json!,
      "primary",
      20
    )};
    --el-color-success: ${this.aiResult.json?.success};
    --el-color-success-light-3: ${this.lighter(
      this.aiResult.json!,
      "success",
      30
    )};
    --el-color-success-light-5: ${this.lighter(
      this.aiResult.json!,
      "success",
      50
    )};
    --el-color-success-light-7: ${this.lighter(
      this.aiResult.json!,
      "success",
      70
    )};
    --el-color-success-light-8: ${this.lighter(
      this.aiResult.json!,
      "success",
      80
    )};
    --el-color-success-light-9: ${this.lighter(
      this.aiResult.json!,
      "success",
      90
    )};
    --el-color-success-dark-2:  ${this.darker(
      this.aiResult.json!,
      "success",
      10
    )};
    --el-color-warning: ${this.aiResult.json?.warning};
    --el-color-warning-light-3: ${this.lighter(
      this.aiResult.json!,
      "warning",
      30
    )};
    --el-color-warning-light-5: ${this.lighter(
      this.aiResult.json!,
      "warning",
      50
    )};
    --el-color-warning-light-7: ${this.lighter(
      this.aiResult.json!,
      "warning",
      70
    )};
    --el-color-warning-light-8: ${this.lighter(
      this.aiResult.json!,
      "warning",
      80
    )};
    --el-color-warning-light-9: ${this.lighter(
      this.aiResult.json!,
      "warning",
      90
    )};
    --el-color-warning-dark-2:  ${this.darker(
      this.aiResult.json!,
      "warning",
      10
    )};
    --el-color-danger: ${this.aiResult.json?.error};
    --el-color-danger-light-3: ${this.lighter(
      this.aiResult.json!,
      "error",
      30
    )};
    --el-color-danger-light-5: ${this.lighter(
      this.aiResult.json!,
      "error",
      50
    )};
    --el-color-danger-light-7: ${this.lighter(
      this.aiResult.json!,
      "error",
      70
    )};
    --el-color-danger-light-8: ${this.lighter(
      this.aiResult.json!,
      "error",
      80
    )};
    --el-color-danger-light-9: ${this.lighter(
      this.aiResult.json!,
      "error",
      90
    )};
    --el-color-danger-dark-2:  ${this.darker(this.aiResult.json!, "error", 10)};
    --el-color-error: ${this.aiResult.json?.error};
    --el-color-error-light-3: ${this.lighter(this.aiResult.json!, "error", 30)};
    --el-color-error-light-5: ${this.lighter(this.aiResult.json!, "error", 50)};
    --el-color-error-light-7: ${this.lighter(this.aiResult.json!, "error", 70)};
    --el-color-error-light-8: ${this.lighter(this.aiResult.json!, "error", 80)};
    --el-color-error-light-9: ${this.lighter(this.aiResult.json!, "error", 90)};
    --el-color-error-dark-2:  ${this.darker(this.aiResult.json!, "error", 10)};
    --el-color-info: ${this.aiResult.json?.textSecondary};
    --el-color-info-light-3: ${this.lighter(
      this.aiResult.json!,
      "textSecondary",
      30
    )};
    --el-color-info-light-5: ${this.lighter(
      this.aiResult.json!,
      "textSecondary",
      50
    )};
    --el-color-info-light-7: ${this.lighter(
      this.aiResult.json!,
      "textSecondary",
      70
    )};
    --el-color-info-light-8: ${this.lighter(
      this.aiResult.json!,
      "textSecondary",
      80
    )};
    --el-color-info-light-9: ${this.lighter(
      this.aiResult.json!,
      "textSecondary",
      90
    )};
    --el-color-info-dark-2:  ${this.darker(
      this.aiResult.json!,
      "textSecondary",
      10
    )};
    --el-color-white: ${this.aiResult.json?.colorWhite};
    --el-color-black: ${this.aiResult.json?.colorBlack};
    --el-bg-color: ${this.aiResult.json?.itemBackground};
    --el-bg-color-page: ${this.aiResult.json?.pageBackground};
    --el-bg-color-overlay: ${this.aiResult.json?.itemBackground};
    --el-text-color-primary: ${this.aiResult.json?.textPrimary};
    --el-text-color-regular: ${this.aiResult.json?.textRegular};
    --el-text-color-secondary: ${this.aiResult.json?.textSecondary};
    --el-text-color-placeholder: ${this.aiResult.json?.textInPlaceholder};
    --el-text-color-disabled: ${this.aiResult.json?.textDisabled};
    --el-menu-text-color: ${this.aiResult.json?.textInMenu};
    --el-menu-hover-text-color: ${this.aiResult.json?.hoverTextInMenu};
    --el-menu-bg-color: ${this.aiResult.json?.menu};
    --el-menu-hover-bg-color: ${this.aiResult.json?.hoverMenu};
    --el-menu-active-color: ${this.aiResult.json?.activeTextInMenu};
    --el-border-color: ${this.aiResult.json?.itemBorderColor};
    --el-border-color-light: ${this.lighter(
      this.aiResult.json!,
      "itemBorderColor",
      30
    )};
    --el-border-color-lighter: ${this.lighter(
      this.aiResult.json!,
      "itemBorderColor",
      50
    )};
    --el-border-color-extra-light: ${this.lighter(
      this.aiResult.json!,
      "itemBorderColor",
      70
    )};
    --el-border-color-dark: ${this.darker(
      this.aiResult.json!,
      "itemBorderColor",
      10
    )};
    --el-border-color-darker: ${this.darker(
      this.aiResult.json!,
      "itemBorderColor",
      30
    )};
    --el-fill-color: ${this.aiResult.json?.itemFill};
    --el-fill-color-light: ${this.lighter(this.aiResult.json!, "itemFill", 30)};
    --el-fill-color-lighter: ${this.lighter(
      this.aiResult.json!,
      "itemFill",
      50
    )};
    --el-fill-color-extra-light: ${this.lighter(
      this.aiResult.json!,
      "itemFill",
      70
    )};
    --el-fill-color-dark: ${this.darker(this.aiResult.json!, "itemFill", 10)};
    --el-fill-color-darker:  ${this.darker(
      this.aiResult.json!,
      "itemFill",
      30
    )};
    --el-fill-color-blank: ${this.aiResult.json?.colorWhite};
    --el-box-shadow: ${this.aiResult.json?.itemBoxShadow};`;
  }

  renderConfigPanel() {
    return html`<main>
      <div class="panel">
        <p>
          请先输入你的文心一言访问令牌，选择希望使用的文心模型，马上就能开始生成啦
        </p>
        <input
          type="text"
          id="access_token"
          name="access_token"
          placeholder="请输入你的文心一言访问令牌"
          ${ref(this.accessTokenRef)}
          @change=${this.cacheAccessToken}
        />
        <div class="radio-group">
          选择模型：
          <label>
            <input
              type="radio"
              name="model"
              value="completions"
              checked
            />文心3.5（更快）
          </label>
          <label>
            <input
              type="radio"
              name="model"
              value="completions_pro"
            />文心4.0（更好）
          </label>
        </div>
        <button @click=${this.begin.bind(this)} class="block-button success">
          开始
        </button>
        <div class="footer">
          <p>提示：你需要使用文心一言的访问令牌来提交请求</p>
          <p>
            你可以在<a
              href="https://aistudio.baidu.com/aistudio/usercenter"
              target="_blank"
              >这里</a
            >获取你的访问令牌
          </p>
          <p>
            项目相关问题反馈请访问<a
              href="https://gitee.com/extrame/ai-theme-maker"
              target="_blank"
              >这里</a
            >，目前已知手机端可能会出现样式问题
          </p>
        </div>
      </div>
    </main>`;
  }

  renderChatPanel() {
    return html`<main>
      <div class="panel">
        <div class="chats">
          <div class="messages">
            ${map(this.messages, (message) =>
              choose(message.role, [
                [
                  "user",
                  () =>
                    html`<div class="message user">
                      <span>${message.content}</span>
                    </div>`,
                ],
                [
                  "assistant",
                  () =>
                    html`<div class="message assistant">
                      <span>${message.content}</span>
                    </div>`,
                ],
                [
                  "loading",
                  () =>
                    html`<div class="message loading">
                      <span>正在加载中...</span>
                    </div>`,
                ],
              ])
            )}
          </div>
        </div>
        <textarea
          id="description"
          name="description"
          placeholder="请输入你的软件介绍或者你希望选取的主色调，比如落日黄，清新蓝等"
        ></textarea>
        <button @click=${this.submit} class="block-button success">提交</button>
      </div>
    </main>`;
  }

  render() {
    return html`
      <div class="top">
        <nav>
          <h1>
            AI配色 <span class="small">使用文心一言为你的软件选择主题配色</span>
          </h1>
          <div class="flex"></div>
          <span @click=${this.selectPage.bind(this, 0)}>配置</span>
          <span @click=${this.selectPage.bind(this, 1)}>对话</span>
          <span @click=${this.selectPage.bind(this, 2)}>预览</span>
          <span @click=${this.selectPage.bind(this, 3)}>导出</span>
        </nav>
      </div>
      ${choose(this.selectedPanel, [
        [0, this.renderConfigPanel.bind(this)],
        [1, this.renderChatPanel.bind(this)],
        [2, this.renderResponse.bind(this)],
        [3, this.renderExportPanel.bind(this)],
      ])}
    `;
  }

  renderExportPanel() {
    return html`<main>
      <div class="panel">
        <p>导出CSS文件</p>
        <div class="radio-group">
          选择适用的前端框架：
          <label>
            <input
              type="radio"
              name="frametype"
              value="element-pro"
              checked
            />Element Pro
          </label>
        </div>
        <button @click=${this.export.bind(this)} class="block-button success">
          导出
        </button>
        <div class="footer">
          <p>导出格式为css文件，定义了主要的框架CSS样式，可以全局导入</p>
        </div>
      </div>
    </main>`;
  }

  darkOrLight(jsonResult: any) {
    var textColor = jsonResult.colorWhite;
    var r = parseInt(textColor.slice(1, 3), 16);
    var g = parseInt(textColor.slice(3, 5), 16);
    var b = parseInt(textColor.slice(5, 7), 16);
    var brightness = Math.round((r * 299 + g * 587 + b * 114) / 1000);
    if (brightness > 125) {
      return "light";
    } else {
      return "dark";
    }
  }

  renderResponse(): unknown {
    // if (this.aiResult && this.aiResult.parsed) {
    const jsonResult = this.aiResult.json;
    if (jsonResult && !jsonResult.colorScheme) {
      this.aiResult.json!.colorScheme = this.darkOrLight(jsonResult);
    }
    return html`
      <div class="response">
        ${when(
          !!jsonResult,
          () => html` <atm-preview
            description=${this.aiResult.description}
            style=${this.pageStyle}
          ></atm-preview>`,
          () => html` <atm-preview
            description=${this.aiResult.description}
            style="color-scheme: light;
    --el-color-primary: #409eff;
    --el-color-primary-light-3: #79bbff;
    --el-color-primary-light-5: #a0cfff;
    --el-color-primary-light-7: #c6e2ff;
    --el-color-primary-light-8: #d9ecff;
    --el-color-primary-light-9: #ecf5ff;
    --el-color-primary-dark-2: #337ecc;
    --el-color-success: #67c23a;
    --el-color-success-light-3: #95d475;
    --el-color-success-light-5: #b3e19d;
    --el-color-success-light-7: #d1edc4;
    --el-color-success-light-8: #e1f3d8;
    --el-color-success-light-9: #f0f9eb;
    --el-color-success-dark-2: #529b2e;
    --el-color-warning: #e6a23c;
    --el-color-warning-light-3: #eebe77;
    --el-color-warning-light-5: #f3d19e;
    --el-color-warning-light-7: #f8e3c5;
    --el-color-warning-light-8: #faecd8;
    --el-color-warning-light-9: #fdf6ec;
    --el-color-warning-dark-2: #b88230;
    --el-color-danger: #f56c6c;
    --el-color-danger-light-3: #f89898;
    --el-color-danger-light-5: #fab6b6;
    --el-color-danger-light-7: #fcd3d3;
    --el-color-danger-light-8: #fde2e2;
    --el-color-danger-light-9: #fef0f0;
    --el-color-danger-dark-2: #c45656;
    --el-color-error: #f56c6c;
    --el-color-error-light-3: #f89898;
    --el-color-error-light-5: #fab6b6;
    --el-color-error-light-7: #fcd3d3;
    --el-color-error-light-8: #fde2e2;
    --el-color-error-light-9: #fef0f0;
    --el-color-error-dark-2: #c45656;
    --el-color-info: #909399;
    --el-color-info-light-3: #b1b3b8;
    --el-color-info-light-5: #c8c9cc;
    --el-color-info-light-7: #dedfe0;
    --el-color-info-light-8: #e9e9eb;
    --el-color-info-light-9: #f4f4f5;
    --el-color-info-dark-2: #73767a;
    --el-bg-color: #ffffff;
    --el-bg-color-page: #f2f3f5;
    --el-bg-color-overlay: #ffffff;
    --el-text-color-primary: #303133;
    --el-text-color-regular: #606266;
    --el-text-color-secondary: #909399;
    --el-text-color-placeholder: #a8abb2;
    --el-text-color-disabled: #c0c4cc;
    --el-border-color: #dcdfe6;
    --el-border-color-light: #e4e7ed;
    --el-border-color-lighter: #ebeef5;
    --el-border-color-extra-light: #f2f6fc;
    --el-border-color-dark: #d4d7de;
    --el-border-color-darker: #cdd0d6;
    --el-fill-color: #f0f2f5;
    --el-fill-color-light: #f5f7fa;
    --el-fill-color-lighter: #fafafa;
    --el-fill-color-extra-light: #fafcff;
    --el-fill-color-dark: #ebedf0;
    --el-fill-color-darker: #e6e8eb;
    --el-fill-color-blank: #ffffff;
    --el-color-white: #ffffff;
    --el-color-black: #000000;
    --el-box-shadow: 0px 12px 32px 4px rgba(0, 0, 0, 0.04), 0px 8px 20px rgba(0, 0, 0, 0.08);
    --el-box-shadow-light: 0px 0px 12px rgba(0, 0, 0, 0.12);
    --el-box-shadow-lighter: 0px 0px 6px rgba(0, 0, 0, 0.12);
    --el-box-shadow-dark: 0px 16px 48px 16px rgba(0, 0, 0, 0.08), 0px 12px 32px rgba(0, 0, 0, 0.12), 0px 8px 16px -8px rgba(0, 0, 0, 0.16);
    --el-disabled-bg-color: var(--el-fill-color-light);
    --el-disabled-text-color: var(--el-text-color-placeholder);
    --el-disabled-border-color: var(--el-border-color-light);
    --el-overlay-color: rgba(0, 0, 0, 0.8);
    --el-overlay-color-light: rgba(0, 0, 0, 0.7);
    --el-overlay-color-lighter: rgba(0, 0, 0, 0.5);
    --el-mask-color: rgba(255, 255, 255, 0.9);
    --el-mask-color-extra-light: rgba(255, 255, 255, 0.3);
    --el-border-width: 1px;
    --el-border-style: solid;
    --el-menu-text-color: #fff;
    --el-menu-hover-text-color: #fff;
    --el-menu-bg-color: #545c64;
    --el-menu-hover-bg-color: rgb(67, 74, 80);
    --el-menu-active-color: #ffd04b;
          "
          ></atm-preview>`
        )}
      </div>
    `;
    // }
  }
}
